<template>
  <el-card class="exam-management-card">
    <div class="card-header">
      <h2>我的考试</h2>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-container">
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        format="YYYY-MM-DD HH:mm:ss"
        value-format="YYYY-MM-DD HH:mm:ss"
        class="date-picker"
      />

      <el-button type="primary" @click="fetchExams">查询</el-button>
      <el-button @click="resetFilter">重置</el-button>
    </div>

    <!-- 考试列表 -->
    <el-table 
      :data="examList" 
      border 
      stripe
      :loading="loading"
      ref="examTableRef"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="40" />
      <el-table-column prop="name" label="考试名称" width="150"/>
      <el-table-column prop="exam_grade" label="所属年级" width="90"/>
      <el-table-column 
        label="所属班级" width="100"
      >
        <template #default="scope">
        {{ scope.row.class_grade }}年级{{ scope.row.class_name }}
        </template>
      </el-table-column>
      <el-table-column prop="deadline" label="提交截止时间" />
      <el-table-column prop="score" label="考试成绩" />
      <el-table-column label="操作" width="250">
        <template #default="scope">
            <el-button 
              type="text" 
              size="small" 
              @click="handleScoreOperation(scope.row)"
            >
            <span 
            :style="{ 
            color: scope.row.has_uploaded ? '' : 'red',
            fontWeight: scope.row.has_uploaded ? '' : 'bold'
            }">
                {{ scope.row.has_uploaded ? '修改成绩' : '录入成绩' }}
            </span>
            </el-button>
          <el-button 
            type="text" 
            size="small" 
            @click="viewStudentRanking(scope.row.exam_id)"
          >
            查看成绩排名
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!-- 底部按钮区域 -->
  <div class="table-footer" v-if="examList.length > 0">
    <el-button
     type="primary"
     size="small"
     @click="handleViewStudentRanking"
     :disabled="selectedExamIds.length === 0"
    >
    查看总分排名
    </el-button>
  </div>

  <!-- 学生成绩排名对话框 -->
   <el-dialog
    v-model="studentRankingDialogVisible"
    :title="isTotalScoreRanking ? '总分排名' : '考试成绩排名'"
    width="800px"
    >
    <div v-if="studentRankingLoading" class="loading-container">
        <el-loading indicator="加载中..." />
    </div>

    <div v-else-if="studentResult" class="result-container">
        <!-- 学生基本信息 -->
        <div class="student-info">
        <p><strong>学生姓名：</strong>{{ studentResult.student_name }}</p>
        <p><strong>所属班级：</strong>{{ studentResult.class_name }}</p>
        <p v-if="studentResult.group_name"><strong>所属小组：</strong>{{ studentResult.group_name }}</p>
        </div>

        <!-- 总分信息（多项考试时显示） -->
        <div v-if="isTotalScoreRanking" class="total-score-section">
        <h3>总分情况</h3>
        <el-descriptions column="1" border>
            <el-descriptions-item label="总分">{{ studentResult.total_score }}</el-descriptions-item>
            <el-descriptions-item label="班级排名">{{ studentResult.total_class_rank || '无' }}</el-descriptions-item>
            <el-descriptions-item label="年级排名">{{ studentResult.total_grade_rank || '无' }}</el-descriptions-item>
            <el-descriptions-item label="小组排名" v-if="studentResult.total_group_rank">{{ studentResult.total_group_rank || '无' }}</el-descriptions-item>
        </el-descriptions>
        </div>

        <!-- 各考试成绩详情 -->
        <div class="exam-results-section">
        <h3>{{ isTotalScoreRanking ? '各考试详情' : '考试详情' }}</h3>
        <el-table :data="studentResult.exam_results" border stripe>
            <el-table-column prop="exam_name" label="考试名称" width="200" />
            <el-table-column prop="score" label="成绩" align="center">
            <template #default="scope">{{ scope.row.score }}</template>
            </el-table-column>
            <el-table-column prop="class_rank" label="班级排名" align="center">
            <template #default="scope">{{ scope.row.class_rank || '无' }}</template>
            </el-table-column>
            <el-table-column prop="grade_rank" label="年级排名" align="center">
            <template #default="scope">{{ scope.row.grade_rank || '无' }}</template>
            </el-table-column>
            <el-table-column prop="group_rank" label="小组排名" align="center" v-if="studentResult.group_id">
            <template #default="scope">{{ scope.row.group_rank || '无' }}</template>
            </el-table-column>
        </el-table>
        </div>
    </div>

    <div v-else class="empty-state">
        暂无成绩数据
    </div>

    <template #footer>
        <el-button @click="studentRankingDialogVisible = false">关闭</el-button>
    </template>
    </el-dialog>

  <!-- 修改成绩和录入成绩共用对话框 -->
  <el-dialog
    v-model="scoreDialogVisible"
    title="录入成绩"
    :close-on-click-modal="false"
    width="500px"
    @close="clearScore"
  >
    <el-form
      :model="scoreForm"
      :rules="scoreRules"
      ref="scoreFormRef"
      label-width="120px"
    >
      <!-- 新成绩输入框 -->
      <el-form-item label="成绩" prop="newScore">
        <el-input
          v-model.number="scoreForm.newScore"
          type="number"
          placeholder="请输入成绩"
          step="0.01"
          :precision="2"
        />
        <div class="form-hint">支持输入小数点后两位</div>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="scoreDialogVisible = false">取消</el-button>
      <el-button
        type="primary"
        @click="handleSaveScore"
        :loading="scoreLoading"
      >
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { ElForm, ElMessage, ElTable, type FormRules } from 'element-plus';
import { 
  listExams, 
  type ListExamsParams, 
  type ExamItem,
  type StudentResultsResponse,
  type StudentResultsParams,
  getStudentResults,
  submitScore,
  type SubmitScoreParams
} from '../../api/exam';

// 筛选条件
const dateRange = ref<string[]>([]);
const loading = ref(false);
const examList = ref<ExamItem[]>([]);

// 页面加载时获取数据
onMounted(async () => {
  await fetchExams();
});

// 查询考试列表
const fetchExams = async () => {
  try {
    loading.value = true;
    const params: ListExamsParams = {};
    
    // 设置时间范围
    if (dateRange.value && dateRange.value.length === 2) {
      params.start_time = dateRange.value[0];
      params.end_time = dateRange.value[1];
    }
    
    const res = await listExams(params);
    if (res.code === 200) {
      examList.value = res.content;
    } else {
      ElMessage.error(res.msg || '获取考试列表失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取考试列表异常');
  } finally {
    loading.value = false;
  }
};

// 重置筛选条件
const resetFilter = () => {
  dateRange.value = [];
  examList.value = [];
};

// 学生排名相关
const studentRankingDialogVisible = ref(false);
const studentRankingLoading = ref(false);
const currentExamId = ref<number>(0);

// 多个考试总分相关
const isTotalScoreRanking = ref(false);
const examTableRef = ref<InstanceType<typeof ElTable>>();
const selectedExamIds = ref<number[]>([]);

// 查看学生成绩排名
const viewStudentRanking = async (examId: number) => {
  currentExamId.value = examId;
  studentRankingDialogVisible.value = true;
  isTotalScoreRanking.value = false;
  
  await fetchStudentRanking(examId);
};

// 成绩操作（录入/修改）
const handleScoreOperation = (examItem: ExamItem) => {
  openScoreDialog({
    examId: examItem.exam_id,
    score: examItem.score
  });
};

// 处理选择变化
const handleSelectionChange = (selection: ExamItem[]) => {
  selectedExamIds.value = selection.map(item => item.exam_id);
};

// 查看学生总分排名
const handleViewStudentRanking = async () => {
  studentRankingDialogVisible.value = true;
  isTotalScoreRanking.value = true;
  
  await fetchStudentRanking();
};

// 学生成绩状态
const studentResult = ref<StudentResultsResponse['content'] | null>(null);

const fetchStudentRanking = async(examId?: number) => {
    try {
        studentRankingLoading.value = true;
        studentResult.value = null; // 重置数据
    
        // 确定请求参数（单个考试或多个考试）
        const params: StudentResultsParams = {
            exam_ids: examId ? [examId] : selectedExamIds.value
        };
        
        const res = await getStudentResults(params);
        if (res.code === 200) {
            studentResult.value = res.content;
        } else {
            ElMessage.error(res.msg || '获取学生排名失败');
        }
    } catch (error: any) {
        ElMessage.error(error.message || '获取学生排名异常');
    } finally {
        studentRankingLoading.value = false;
    }
};

// 成绩表单数据类型
interface ScoreForm {
  examId: number;
  studentId: number;
  studentName: string;
  oldScore?: number | null;
  newScore: number;
}

// 状态管理
const scoreDialogVisible = ref(false);
const isScoreEditMode = ref(false); // true:修改成绩, false:录入成绩
const scoreLoading = ref(false);
const scoreFormRef = ref<InstanceType<typeof ElForm>>();

// 表单数据
const scoreForm = reactive<ScoreForm>({
  examId: 0,
  studentId: 0,
  studentName: '',
  oldScore: null,
  newScore: 0
});

// 表单验证规则
const scoreRules: FormRules<ScoreForm> = {
  newScore: [
    { required: true, message: '请输入成绩', trigger: 'blur' },
    { type: 'number', message: '请输入有效的数字', trigger: 'blur' }, // 此时 type 会被正确识别为 RuleType
    { 
      validator: (_, value: number, callback) => {
        if (value < 0) {
          callback(new Error('成绩不能为负数'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

interface OpenScoreDialogParams {
  examId: number;
  score?: number;
}

// 打开录入成绩对话框
const openScoreDialog = (params: OpenScoreDialogParams) => {
  // 重置表单
  Object.assign(scoreForm, {
    examId: params.examId,
    newScore: params.score
  });
  
  scoreDialogVisible.value = true;
};

// 保存成绩
const handleSaveScore = async () => {
  if (!scoreFormRef.value) return;

  try {
    scoreLoading.value = true;
    await scoreFormRef.value.validate();

    // 构造请求参数
    const params: SubmitScoreParams = {
      exam_id: scoreForm.examId,
      score: scoreForm.newScore
    };

    const res = await submitScore(params);
    if (res.code === 200) {
      scoreDialogVisible.value = false;
      ElMessage.success(isScoreEditMode.value ? '成绩修改成功' : '成绩录入成功');
      // 刷新考试列表
      await fetchExams();
    } else {
      ElMessage.error(res.msg || (isScoreEditMode.value ? '修改失败' : '录入失败'));
    }
  } catch (error: any) {
    ElMessage.error(error.message || '操作异常');
  } finally {
    scoreLoading.value = false;
  }
};

const clearScore = () => {
    scoreForm.oldScore = 0;
    scoreForm.newScore = 0;
}
</script>

<style scoped>
.exam-management-card {
  margin: 20px;
  background-color: #f0f2f5;
  max-width: 1400px; /* 增加最大宽度限制 */
  margin-left: auto; /* 居中显示 */
  margin-right: auto; /* 居中显示 */
  width: 1000px;
}

.card-header {
  margin-bottom: 15px;
  display: flex;       /* 启用Flex布局 */
  justify-content: space-between;  /* 两端对齐，标题居左，按钮居右 */
}

.card-header h2 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.filter-container {
  display: flex;
  gap: 15px;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  width: 550px;
}

.date-picker {
  width: 300px;
}

/* 新增底部按钮样式 */
.table-footer {
  display: flex;
  gap: 10px;
  padding: 12px 16px;
  justify-content: flex-end;
  border-top: 1px solid #eee;
  margin-top: -1px;
}

.filter-card {
  margin-bottom: 20px;
  padding: 15px;
}

.form-hint {
  color: #606266;
  font-size: 12px;
  margin-top: 5px;
}

/* 排名对话框样式 */
.loading-container {
  text-align: center;
  padding: 50px 0;
}

.result-container {
  padding: 10px 0;
}

.student-info {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.student-info p {
  margin: 5px 0;
}

.total-score-section {
  margin-bottom: 20px;
}

.total-score-section h3,
.exam-results-section h3 {
  font-size: 14px;
  margin-bottom: 10px;
  color: #1f2329;
  font-weight: 600;
}

.empty-state {
  text-align: center;
  padding: 50px 0;
  color: #909399;
}

@media (max-width: 768px) {
  .filter-container {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-select, .date-picker {
    width: 100%;
  }
}
</style>